package com.xs.ahoi.hcxs.ui.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.ui.fragment.BookCityFragment;
import com.xs.ahoi.hcxs.ui.fragment.BookShelfFragment;
import com.xs.ahoi.hcxs.ui.fragment.UserFragment;
import com.xs.ahoi.hcxs.ui.view.NoScrollViewPager;
import com.xs.ahoi.hcxs.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class IndexActivity extends BaseActivity {

    @BindView(R.id.layoutTab)
    public TabLayout layoutTab;
    @BindView(R.id.viewpager)
    public NoScrollViewPager viewpager;

    // 加入fragment
    private List<Fragment> fragments;
    private String[] titles = {"书架", "书城", "我的"};
    private int[] icons = {R.drawable.icon_book_shelf, R.drawable.icon_book_city, R.drawable.icon_my};
    private int[] iconsSelect = {R.drawable.icon_book_shelf_select, R.drawable.icon_book_city_selected, R.drawable.icon_my_select};
    // 用于存放上一点击返回键的时刻
    private long lastClickBackTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        ButterKnife.bind(this);
        init();
    }


    @Override
    protected void onResume() {
        super.onResume();
        BookShelfFragment fragment = (BookShelfFragment) fragments.get(0);
        fragment.init();
    }

    private void init() {
        initFragments();
        initListener();
        initTabIcons();
    }

    // 初始化tab点击监听
    private void initListener() {
        layoutTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setTabSelect(tab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                setTabNormal(tab);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    // 初始化图标
    private void initTabIcons() {
        layoutTab.getTabAt(0).setCustomView(getTabView(0));
        layoutTab.getTabAt(1).setCustomView(getTabView(1));
        layoutTab.getTabAt(2).setCustomView(getTabView(2));
    }

    // 设置tab为选中状态
    private void setTabSelect(TabLayout.Tab tab) {
        View view = tab.getCustomView();
        TextView tvTitle = view.findViewById(R.id.tvTitle);
        ImageView ivTitle = view.findViewById(R.id.ivTitle);
        tvTitle.setTextColor(ContextCompat.getColor(this, R.color.colorRed));
        ivTitle.setImageResource(iconsSelect[tab.getPosition()]);
    }

    // 设置tab为未选中状态
    private void setTabNormal(TabLayout.Tab tab) {
        View view = tab.getCustomView();
        TextView tvTitle = view.findViewById(R.id.tvTitle);
        ImageView ivTitle = view.findViewById(R.id.ivTitle);
        tvTitle.setTextColor(ContextCompat.getColor(this, R.color.colorBlackLittle));
        ivTitle.setImageResource(icons[tab.getPosition()]);
    }

    // 获取tablayout的自定义view
    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.fragment_tab_index, null);
        TextView tvTitle = view.findViewById(R.id.tvTitle);
        ImageView ivTitle = view.findViewById(R.id.ivTitle);
        tvTitle.setText(titles[position]);
        if (position == 0) {
            ivTitle.setImageResource(iconsSelect[position]);
            tvTitle.setTextColor(ContextCompat.getColor(this, R.color.colorRed));
        } else {
            ivTitle.setImageResource(icons[position]);
            tvTitle.setTextColor(ContextCompat.getColor(this, R.color.colorBlackLittle));
        }
        return view;
    }

    private void initFragments() {
        fragments = new ArrayList<>();
        fragments.add(getBookShelfFragment());
        fragments.add(getBookCityFragment());
        fragments.add(getUserFragment());
        MyTabLayoutAdapter adapter = new MyTabLayoutAdapter(getSupportFragmentManager(), fragments, titles);
        viewpager.setAdapter(adapter);
        viewpager.setNoScroll(true);
        layoutTab.setupWithViewPager(viewpager);
    }

    private BookShelfFragment getBookShelfFragment() {
        BookShelfFragment fragment = new BookShelfFragment();
        fragment.setCallbackListener(() -> IndexActivity.this.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out));
        return fragment;
    }

    private UserFragment getUserFragment() {
        return new UserFragment();
    }

    private BookCityFragment getBookCityFragment() {
        return new BookCityFragment();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 获取到Activity下的Fragment
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        // 查找在Fragment中onRequestPermissionsResult方法并调用
        for (Fragment fragment : fragments) {
            if (fragment != null) {
                // 这里就会调用我们Fragment中的onRequestPermissionsResult方法
                fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - lastClickBackTime) > 2000) {
            ToastUtil.show("再按一次退出程序");
            lastClickBackTime = System.currentTimeMillis();
        } else {
            super.removeAll();
        }
    }

    // 自定义adapter
    private class MyTabLayoutAdapter extends FragmentPagerAdapter {

        private List<Fragment> mFragmentList;
        private String[] mTitles;

        public MyTabLayoutAdapter(FragmentManager mFragmentManager, List<Fragment> fragmentList, String[] titles) {
            super(mFragmentManager);
            mFragmentList = fragmentList;
            mTitles = titles;
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        @Override
        public Fragment getItem(int position) {
            if (position < mFragmentList.size()) {
                return mFragmentList.get(position);
            }
            return mFragmentList.get(0);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }
    }
}
